package com.codeoss.module.res.service.impl;

import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.codeoss.framework.context.YunContext;
import com.codeoss.framework.view.model.HierarchyData;
import com.codeoss.framework.view.util.DataSourceUtil;
import com.codeoss.module.res.model.ResRelRoleOrg;
import com.codeoss.module.res.request.RelRoleOrgPageRequest;
import com.codeoss.module.res.response.RelRoleOrgPageResponse;
import com.codeoss.module.res.service.IRelRoleOrgPageService;
import com.codeoss.module.res.service.IResOrgService;
import com.codeoss.module.res.service.IResRelRoleOrgService;

@Service
public class RelRoleOrgPageService implements IRelRoleOrgPageService {
    @Autowired
    private IResOrgService resOrgService;
    @Autowired
    private IResRelRoleOrgService resRelRoleOrgService;
    @Autowired
   	private DataSourceUtil dataSourceUtil;
	@Override
	public RelRoleOrgPageResponse init(Long resRoleId) {
		// TODO Auto-generated method stub
		RelRoleOrgPageResponse relRoleOrgPageResponse=new RelRoleOrgPageResponse();
		YunContext yunContext=YunContext.getCurrentContext();
		List<Map<String, Object>> dataList= resOrgService.listMaps();
		HierarchyData  menuData=dataSourceUtil.convertTableDataToHierarchyData(yunContext, dataList);
		relRoleOrgPageResponse.setMenuData(menuData);
		
		List<Long> valueList=resRelRoleOrgService.getOrgIdListByRoleId(resRoleId);
		relRoleOrgPageResponse.setValueList(valueList);
		
		return relRoleOrgPageResponse;
	}
	@Override
	@Transactional
	public RelRoleOrgPageResponse dataSave(RelRoleOrgPageRequest request) {
		// TODO Auto-generated method stub
		RelRoleOrgPageResponse relRoleOrgPageResponse=new RelRoleOrgPageResponse();
		QueryWrapper<ResRelRoleOrg> queryWrapper=new QueryWrapper<ResRelRoleOrg>();
		queryWrapper.eq("res_role_id", request.getResRoleId());
		resRelRoleOrgService.remove(queryWrapper);
		List<Long> valueList=request.getValueList();
		if(valueList!=null) {
			for(int i=0;i<valueList.size();i++) {
				ResRelRoleOrg resRelRoleOrg=new ResRelRoleOrg();
				resRelRoleOrg.setResRoleId(request.getResRoleId());
				resRelRoleOrg.setResOrgId2(valueList.get(i));
				resRelRoleOrgService.insert(resRelRoleOrg);
			}
		}
		return relRoleOrgPageResponse;
	}

}
